package com.xtedu.examproject.controller;

import cn.hutool.json.JSONObject;
import com.google.gson.Gson;
import com.xtedu.examproject.entity.Role;
import com.xtedu.examproject.entity.Teacher;
import com.xtedu.examproject.service.RoleService;
import com.xtedu.examproject.util.PageHelper;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/authmanage/*")
public class RoleServlet extends HttpServlet {
    private RoleService roleService;
    private final static int pageSize = 5;

    public void init() {
        roleService = new RoleService();
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        // 获取路径信息
        String pathInfo = req.getPathInfo();
        // 处理路径信息
        String path = (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) ? "/" : pathInfo;
        try {
            switch (path) {
                case "/addRoleType":
                    addRoleType(req, resp);
                    break;
                case "/deleteRole":
                    deleteRole(req, resp);
                    break;
                    case "/updateRole":
                        updateRole(req, resp);
                        break;
                default:
                    showRoleManage(req, resp);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        // 获取路径信息
        String pathInfo = req.getPathInfo();

        try {
            if (pathInfo == null || pathInfo.equals("/") || pathInfo.equals("")) {
                showRoleManage(req, resp);
            } else if (pathInfo.equals("/addRoleType")) {
                // 处理添加课程表单提交
                addRoleType(req, resp);
            } else if (pathInfo.equals("/deleteRole")) {
                deleteRole(req, resp);
            } else if (pathInfo.equals("/updateRole")) {
                updateRole(req, resp);
            } else {
                showRoleManage(req, resp);
            }
        } catch (Exception e) {
            throw new ServletException("处理请求失败", e);
        }
    }

    /**
     * 添加角色
     *
     * @param req
     * @param resp
     * @throws Exception
     */
    private void addRoleType(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            // 读取请求体中的JSON数据
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // 解析JSON数据
            Gson gson = new Gson();
            Role role = gson.fromJson(sb.toString(), Role.class);
            roleService.insert(role);

            // 返回成功响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", true);
            responseJson.put("message", "老师信息添加成功");
            resp.getWriter().write(responseJson.toString());

        } catch (
                Exception e) {
            // 返回错误响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "添加老师信息失败: " + e.getMessage());
            resp.getWriter().write(responseJson.toString());
        }
    }

    /**
     * 处理老师管理页面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void showRoleManage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            int pageIndex = req.getParameter("pageIndex") != null ? Integer.parseInt(req.getParameter("pageIndex")) : 1;
            PageHelper page = roleService.findAllByPage(pageIndex, pageSize);

            // 构造完整的servlet名称，如果存在路径信息则将其与servlet路径拼接，否则直接使用servlet路径
            String servletName = req.getPathInfo() != null ? req.getServletPath() + req.getPathInfo() : req.getServletPath();
            page.setServletName(servletName);
            // 获取所有老师数据
            req.setAttribute("page", page);
        } catch (Exception e) {
            throw new ServletException("获取老师数据失败", e);
        }
        // 转发到老师管理页面
        req.getRequestDispatcher("/WEB-INF/views/rolemanage.jsp").forward(req, resp);
    }

    /**
     * 删除角色
     *
     * @param req
     * @param resp
     * @throws ServletException
     */
    public void deleteRole(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        try {
            // 设置响应类型为JSON
            resp.setContentType("application/json;charset=UTF-8");
            resp.setCharacterEncoding("UTF-8");

            // 获取要删除的课程ID
            String RoleId = req.getParameter("id");

            // 检查课程ID是否为空
            if (RoleId != null && !RoleId.isEmpty()) {
                try {
                    int roleId = Integer.parseInt(RoleId);

                    // 调用service层方法删除课程
                    boolean deleted = roleService.deleteRoleById(roleId);

                    // 返回JSON响应
                    if (deleted) {
                        resp.getWriter().write("{\"success\":true,\"message\":\"课程删除成功\"}");
                    } else {
                        resp.getWriter().write("{\"success\":false,\"message\":\"课程删除失败，可能课程不存在\"}");
                    }
                } catch (NumberFormatException e) {
                    resp.getWriter().write("{\"success\":false,\"message\":\"课程ID格式错误\"}");
                }
            } else {
                resp.getWriter().write("{\"success\":false,\"message\":\"无效的课程ID\"}");
            }
        } catch (Exception e) {
            System.err.println("删除课程时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 编辑角色信息
     * @param req
     * @param resp
     * @throws ServletException
     */
    public void updateRole(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        try {
            // 读取请求体中的JSON数据
            StringBuilder sb = new StringBuilder();
            String line;
            BufferedReader reader = req.getReader();
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

            // 解析JSON数据
            Gson gson = new Gson();
            Role role = gson.fromJson(sb.toString(), Role.class);

            // 检查必要字段
            if (role.getId() <= 0 || role.getRoleName() == null || role.getRoleName().trim().isEmpty()) {
                // 返回错误响应
                JSONObject responseJson = new JSONObject();
                responseJson.put("success", false);
                responseJson.put("message", "角色ID和名称不能为空");
                resp.setContentType("application/json;charset=UTF-8");
                resp.getWriter().write(responseJson.toString());
                return;
            }

            // 调用service层方法更新角色信息
            boolean updated = roleService.updateRole(role);

            // 返回响应
            JSONObject responseJson = new JSONObject();
            if (updated) {
                responseJson.put("success", true);
                responseJson.put("message", "角色信息更新成功");
            } else {
                responseJson.put("success", false);
                responseJson.put("message", "角色信息更新失败");
            }

            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(responseJson.toString());

        } catch (Exception e) {
            // 返回错误响应
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "更新角色信息失败: " + e.getMessage());
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(responseJson.toString());
        }
    }

}
